<template>
	<view>
		<u-notice-bar mode="closable" :text="text1"></u-notice-bar>
		<view class="add-shop-box" @click.stop="addShop">
			<u-icon name="plus" size="28" color="#FFF"></u-icon>
		</view>

		<scroll-view style="height: 95vh;" scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered"
			@scrolltolower="scrolltolower" :refresher-threshold="40" @refresherpulling="onPulling"
			@refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort">
			<list loadmoreoffset="10" ref="list" class="list-father">

				<cell v-for="(item,index) in shopList" :key="item.id">
					<view class="list-item">
						<view class="list-item-head">
							<view class="list-item-head-left">
								<image class="list-item-head-left-img" :src="item.img[0]" mode="aspectFit"></image>
							</view>
							<view class="list-item-head-right">
								<view class="list-item-haed-right-head">
									{{item.introduce}}
								</view>
								<view class="list-item-head-right-center">
									<text>已售{{item.hot}}</text> <text class="m">|</text>
									<text>剩余库存{{item.shop_number - item.hot}}</text>
								</view>
								<view class="list-item-head-right-bottom">
									￥{{parseInt(item.price).toFixed(2)}}
								</view>
								<view class="list-item-head-right-time">
									{{item.pb_time}}
								</view>
							</view>
						</view>
						<view class="list-item-bottom"  v-if="item.ispublic === '0'">
							<view class="list-item-bottom-left">
								等待审核
							</view>
						</view>
						<view class="list-item-bottom" @click="delectShop(item.id)" v-else-if="item.ispublic === '1'">
							<view class="list-item-bottom-left">
								下架商品
							</view>
						</view>
						<view class="list-item-bottom" @click="delectShop(item.id)"  v-else>
							<view class="list-item-bottom-left">
								审核失败，点击删除商品
							</view>
						</view>
					</view>
				</cell>

			</list>
			<view class="bottom">
				<u-loadmore :status="status" :icon="true" v-if="isShow" :loadingText="loadingText"
					@loadmore="loadmore" />
			</view>
		</scroll-view>



		<u-overlay :show="show">
			<view class="warp">

				<view class="content">
					<view class="content-head">
						<view class="content-head-h">
							闲置图片<text class="content-head-h-span">(注意，默认第一张为闲置列表展示)</text>
						</view>
						<uni-file-picker @delete="delShop" limit="3" v-model="shopImage" fileMediatype="image"
							mode="grid" @select="shopImgSelect" />
					</view>
					<view class="content-content">
						<view class="content-content-left">
							闲置介绍:
						</view>
						<view class="content-content-right">
							<u--textarea border="bottom" :maxlength="50" v-model="shop.introduce"
								placeholder="注意,为闲置列表展示" autoHeight></u--textarea>
						</view>
					</view>
					<view class="content-content">
						<view class="content-content-left">
							详细介绍:
						</view>
						<view class="content-content-right">
							<u--textarea border="bottom" :maxlength="300" v-model="shop.detail_introduce"
								placeholder="注意,为闲置内容详细展示" count></u--textarea>
						</view>
					</view>
					<view class="content-content">
						<view class="content-content-left">
							单价:
						</view>
						<view class="content-content-right">
							<u--input placeholder="请输入单件商品价格" border="surround" type="number" v-model="shop.price">
							</u--input>
						</view>
					</view>
					<view class="content-content">
						<view class="content-content-left">
							闲置数量:
						</view>
						<view class="content-content-right">
							<u--input placeholder="请输入闲置数量" border="surround" type="number" v-model="shop.shop_number">
							</u--input>
						</view>
					</view>
					<view class="content-content">
						<view class="content-content-left">
							闲置分类:
						</view>
						<view class="content-content-right">
							<input :disabled="true" @click="changeClassifyFlag" placeholder="请选择闲置分类" v-model="classify"
								border="surround" ></input>
						</view>
					</view>
					<view class="content-content2">
						<view class="content-content-btn">
							<u-button open-type="getPhoneNumber" @getphonenumber="getUserPhone" shape="circle"
								:loading="isSusAdd" style="width: 300px;" :size="'large'" type="primary" text="确认发布">
							</u-button>

						</view>
						<view class="content-content-btn">
							<u-button @click="canceAddShop" shape="circle" style="width: 300px;" :size="'large'"
								type="warning " text="取消发布"></u-button>

						</view>


					</view>
				</view>
			</view>

		</u-overlay>

		<uni-fab :horizontal="'right'" :vertical="'bottom'" @fabClick="addShop"></uni-fab>
		<u-picker @confirm="changeClassifyShop" @cancel="clsoeClassifyFlag" :show="classifyFlag" :columns="columns">
		</u-picker>


		<u-popup :mode="'center'" :show="propsShow" :closeOnClickOverlay="false" @open="open">
			<view class="props-box">
				<view class="props-box-text">
					资格申请
				</view>

				<view class="props-box-text2">
					收款码:
				</view>
				<uni-file-picker @delete="addDelShop" limit="1" v-model="addImage" fileMediatype="image" mode="grid"
					@select="addImgSelect" />
				<view class="props-box-bottom">
					<view class="btn1">
						<u-button open-type="getPhoneNumber" @getphonenumber="getUserPhoneFun" type="primary"
							text="确定申请"></u-button>
					</view>
					<u-button type="primary" @click="this.propsShow = false" plain text="取消"></u-button>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				refreshText: '下拉刷新',
				page: 1,
				flag: false,
				show: false,
				classifyFlag: false,
				shopImage: [],
				shop: {
					introduce: '',
					detail_introduce: '',
					price: '',
					shop_number: '',
					classify: '',
					img: []
				},
				classify: '',
				columns: [
					['生活', '花店',  '电子设备']
				],
				isSusAdd: false,
				refreshing: false,
				shopList: [],
				addShopFlag: false,
				returnTop: false,
				scrollTop: 0,
				toTop: {
					'right': '220px',
					'bottom': '400px'
				},
				code: '',
				mobile: '',
				triggered: false,
				_freshing: false,
				status: 'loadmore',
				isShow: false,
				propsShow: false,
				isBusiness: false,
				list: [],
				addImage: [],
				text1: '抱歉，由于微信审核原因，商品不能是食品类的和图书类的'
			};
		},
		onPullDownRefresh() {

		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onLoad() {
			this.isShow = false
			this._freshing = false;
			this.getMyShop()
			this.triggered = true;
			this.isShow = true
			this.judgeBusiness()
			this.getCode()
		},
		methods: {
			scrolltolower() {
				uni.$u.throttle(this.getMyShop, 500)
			},
			// 删除图片
			addDelShop(event) {
				this.addImage = []
			},
			addImgSelect(e) {
				e.tempFiles.forEach((item) => {
					let obj = {
						name: item.name,
						uri: item.url
					}
					this.addImage.push(obj)
				})
			},
			// 判断是否为商家
			async judgeBusiness() {
				try {
					const {
						data: res
					} = await uni.$http.get('/shop/judgeBusiness');
					if (res.status !== 0) return this.addBusiness()
					this.isBusiness = true
				} catch (e) {
					uni.showToast({
						icon: 'none',
						title: e
					})
				}
			},
			// 不是商家要求上传收款码
			async addBusiness() {
				uni.showModal({
					title: '申请资格',
					content: '检测到您还没有资格，是否立刻上传收款码申请',
					success: (res) => {
						if (res.confirm) {
							this.propsShow = true
						}
					}
				})
			},
			// 先获取用户的手机号
			async getUserPhoneFun(e) {
				try {
					const {
						iv,
						encryptedData
					} = e.detail
					if (this.addImage.length === 0) return uni.showToast({
						icon: 'none',
						title: '请上传收款码',
						duration: 2000
					})
					if (!this.code || !iv || !encryptedData) return uni.showToast({
						icon: 'none',
						title: '为了保护用户权益，发布闲置必须获得您的手机号',
						duration: 2000
					})
					const {
						data: res
					} = await uni.$http.post('/pay/getUserPhone', {
						code: this.code,
						encryptedData: encryptedData,
						iv: iv
					})
					if (res.status !== 200) return uni.showToast({
						icon: 'none',
						title: res.message
					})
					this.mobile = res.data.phoneNumber
					this.propsShow = false
					uni.uploadFile({
						url: 'https://www.apricity.asia:8911/shop/addBusinessUser',
						filePath: this.addImage[0].uri,
						name: this.addImage[0].name,
						formData: {
							'mobile': this.mobile
						},
						header: {
							Authorization: uni.getStorageSync('token')
						},
						success: (res) => {
							if (JSON.parse(res.data).status !== 200) return uni.showToast({
								title: JSON.parse(res.data).message,
								icon: 'none'
							})
							uni.showToast({
								icon: 'none',
								title: '恭喜您成为闲置会员',
								duration: 2000
							})
							this.isBusiness = true
						},
						fail(e2) {
							console.log(e2)
							return uni.showToast({
								title: e2,
								icon: 'none'
							})
						}
					})
				} catch (e) {
					uni.showToast({
						icon: 'none',
						title: '发布闲置必须获得您的手机号'
					})
				}
			},
			loadmore() {
				if (this.shopList.length === 0) {
					this.loadmoreText = '没有更多了'
				}
			},
			onPulling(e) {

			},
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				this.isShow = false
				this.shopList = []
				this.page = 1
				this.getMyShop()
				this.triggered = false;
				this._freshing = false;
				this.isShow = true
			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置

			},
			onAbort() {

			},
			/*
				下架商品
			*/
			delectShop(id) {
				let _this = this
				uni.showModal({
					title: '下件商品?',
					content: '您真的要下架这个商品吗?',
					success: async (e) => {
						if (e.confirm) {
							try {
								const {
									data: res
								} = await uni.$http.get(`/shop/deluserpbshop/${id}`)
								if (res.status !== 0) return uni.showToast({
									icon: 'none',
									title: res.message,
									duration: 2000
								})
								_this.onRefresh()
								return uni.showToast({
									icon: 'success',
									title: '下架成功',
									duration: 2000
								})
							} catch (e) {
								return uni.showToast({
									icon: 'fail',
									title: '未知错误',
									duration: 2000
								})
							}
						}
					}
				})

			},
			reFresh() {
				console.log('点击了')
			},
			downCallback() {
				this.shopList = []
				this.page = 1
				try {
					this.mescroll.resetUpScroll();
				} catch (e) {

				}
			},
			// get code
			getCode() {
				wx.login({
					success: (res) => {
						this.code = res.code
					}
				})
			},
			// 新增前获取手机号
			async getUserPhone(e) {
				try {
					const {
						iv,
						encryptedData
					} = e.detail
					if (!this.isBusiness) return this.addBusiness()
					if (!this.code || !iv || !encryptedData) return uni.showToast({
						icon: 'none',
						title: '为了保护用户权益，发布闲置必须获得您的手机号',
						duration: 2000
					})
					if (this.mobile.length !== 0) return this.addNewShop(this.mobile)
					const {
						data: res
					} = await uni.$http.post('/pay/getUserPhone', {
						code: this.code,
						encryptedData: encryptedData,
						iv: iv
					})
					if (res.status !== 200) return uni.showToast({
						icon: 'none',
						title: res.message
					})
					this.mobile = res.data.phoneNumber
					this.addNewShop()
				} catch (e) {
					uni.showToast({
						icon: 'none',
						title: '发布闲置必须获得您的手机号'
					})
				}
			},
			/*
				订阅
			*/
			subscrShop(tplids) {
				uni.requestSubscribeMessage({
					tmplIds: [tplids],
					success: async (res) => {
						if (res[tplids] !== 'accept') return
						let prames = {
							code: this.code,
							template_id: tplids
						}
						const {
							data: res2
						} = await uni.$http.post('/message/addWenXinMessage', prames)
						console.log(res2)
			 		if (res2.status !== 200) return uni.showToast({
							icon: 'none',
							title: '订阅失败',
							duration: 2000
						})
					uni.showToast({
						icon: 'none',
						title: '订阅成功',
						duration: 2000
					})
					},
					fail: (res) => {
						console.log(res)
					},
					complete: (res) => {
						
					}
				})
			},
			/*
				新增商品
			*/
			addNewShop() {
				if (this.shopImage.length < 2) return uni.showToast({
					icon: 'none',
					title: '图片最少2张',
					duration: 2000
				})
				let list = []
				this.shopImage.forEach((item) => {
					list.push(item.url)
				})
				setTimeout(async () => {
					this.shop.img = list.join('@@')
					if (this.shop.introduce.length === 0 || this.shop.detail_introduce
						.length === 0 || this.shop.shop_number.length === 0 || this.shop.classify.length === 0) return uni.showToast({
							icon: 'error',
							title: '请输入',
							duration: 2000
						})
					if (this.shop.img.length < 2) return uni.showToast({
						icon: 'error',
						title: '最少2张图片',
						duration: 2000
					})
					this.shop = {
						...this.shop,
						mobile: this.mobile
					}
					try {
						this.isSusAdd = true
						const {
							data: res
						} = await uni.$http.post('/shop/addshop', this.shop)
						this.isSusAdd = false
						if (res.status !== 0) return uni.showToast({
							icon: 'none',
							title: res.message,
							duration: 2000
						})
						uni.showModal({
							title: '发布成功等待审核',
							content: '是否订阅审核结果?',
							success: (res2) => {
								if (res2.confirm) {
									this.getCode()
									this.subscrShop('3C7iy-Evo745aECqwwTvkuIBmGnTLsXSLUVC01aQ3m8')
								}
							}
						})
						uni.showModal({
							title: '订单通知',
							content: '是否订阅有新的订单?',
							success: (res2) => {
								if (res2.confirm) {
									this.getCode()
									this.subscrShop('5bM_49ov0CVu2QEhL5nQze2goSWx3Jwg08fCvyMyDiE')
								}
							}
						})
					} catch (e) {
						this.isSusAdd = false
						return uni.showToast({
							icon: 'none',
							title: '发布失败',
							duration: 2000
						})
					}
				},50)
				
			},
			/*
				选择分类选择器内容
			*/
			changeClassifyShop(e) {
				this.classify = e.value[0]
				this.shop.classify = e.value[0]
				this.classifyFlag = false
			},
			/*
				打开分类选择器
			*/
			changeClassifyFlag() {
				console.log('ok123456789')
				this.classifyFlag = true
			},
			/*
				关闭分类选择器
		   */
			clsoeClassifyFlag() {
				this.classifyFlag = false
			},
			compress(img) {
				console.log('OK2')
				let that = this

			},
			/*
				商品图片选择
			*/
			shopImgSelect(e) {
				if (this.shop.img.length === 0) {
					e.tempFiles.forEach((item) => {
						let obj = {
							name: item.name,
							uri: item.url
						}
						this.shop.img.push(obj)
					})
					return
				}
				e.tempFiles.forEach((item) => {
					this.shop.img.forEach((item2) => {
						if (item.name === item2.name) {

						} else {

							let obj = {
								name: item.name,
								uri: item.url
							}
							this.shop.img.push(obj)
						}
					})
				})
			},
			/*
				商品图片删除
		   */
			delShop(e) {
				let resultIndex = this.shop.img.findIndex((item) => {
					return item.name === e.tempFile.name
				})
				if (resultIndex === -1) return
				this.shop.img.splice(resultIndex, 1)
			},
			/*
				取消发布商品按钮
			*/
			canceAddShop() {
				this.show = false
			},
			/*
				点击发布商品按钮
			*/
			addShop() {
				this.show = true
			},
			/*
				获取我发布的商品
			*/
			async getMyShop() {
				try {
					const {
						data: res
					} = await uni.$http.get(`/shop/getuserpbshop/${this.page}`)
					if (res.status !== 0) return uni.showToast({
						icon: 'none',
						title: res.message,
						duration: 2000
					})
					if (res.data.length === 0 || res.length === 0) {
						this.status = 'nomore';
					}
					this.shopList = [...this.shopList, ...res.data]
					this.page++
				} catch (e) {

				}

			}
		}
	}
</script>

<style lang="scss" scoped>
	// 文件上传
	.props-box {
		margin: 30px 80px;

		.props-box-text {
			font-size: 18px;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 10px;
		}

		.props-box-text2 {
			margin-bottom: 5px;
		}

		.props-box-bottom {
			margin-top: 20px;
			display: flex;
			align-items: center;
			justify-content: space-between;

			/deep/ .btn1 {
				margin-right: 10px !important;
			}
		}
	}

	.add-shop-box {
		display: flex;
		z-index: 999;
		height: 40px;
		width: 40px;
		position: fixed;
		right: 3%;
		bottom: 15%;
		background-color: #3C9CFF;
		border-radius: 50%;
		align-items: center;
		justify-content: center;
	}

	/deep/.mescroll-totop {
		right: 7% !important;
		bottom: 12% !important;
	}

	.list-item-head-right-time {
		font-size: 12px;
		color: #C4C6C9;
		margin-top: 5px;
	}

	.u-page {
		overflow-y: auto;
	}

	.m {
		margin: 0 5px;
	}

	.list-father {
		height: 500rpx;
		width: 500px;

		.list-item {
			background-color: #FFFFFF;
			width: 90%;
			margin: 5px 5% 10px 5%;
			border-radius: 5px;

			.list-item-head {
				padding: 8px 8px;
				display: flex;
				align-items: center;
				justify-content: left;

				.list-item-head-left {
					width: 120px;
					height: 120px;
					margin-right: 15px;

					.list-item-head-left-img {
						width: 120px;
						height: 120px;
					}
				}

				.list-item-head-right {
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;

					.list-item-haed-right-head {
						font-size: 16px;
						color: #303133;
						margin-bottom: 5px;

					}

					.list-item-head-right-center {
						font-size: 12px;
						color: #909399;
						margin-bottom: 15px;
					}

					.list-item-head-right-bottom {
						font-size: 16px;
						color: #f1a532;
					}
				}
			}

			.list-item-bottom {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 50px;
				border-top: 2px solid #eeeeee;
				padding: 0 !important;

				.list-item-bottom-left {
					color: #767a82;
					font-size: 14px;
				}
			}
		}
	}

	.content {
		background-color: #FFFFFF;

		.content-head {
			margin: 0 15px;
			padding: 15px 0;

			.content-head-h {
				font-size: 16px;
				font-weight: bold;
				margin-bottom: 5px;

				.content-head-h-span {
					font-size: 12px;
					color: #c4c6c9;
				}
			}

			border-top: 2px solid #f4f4f5;
			border-bottom: 2px solid #f4f4f5;
		}

		.content-content {
			display: flex;
			align-items: center;
			justify-content: left;
			margin: 0 15px;
			padding: 5px 0;

			border-bottom: 2px solid #f4f4f5;

			.content-content-left {
				width: 25%;
			}

			.content-content-right {
				width: 75%;
			}
		}

	}

	.content-content2 {
		margin: 0 15px;
		padding: 5px 0;

		.content-content-btn {
			margin-top: 10px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	.transition {
		width: 30px;
		height: 30px;
		border-radius: 30px;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		z-index: 999;
		right: 7%;
		background-color: #f4f4f5;
		bottom: 15%;
	}

	/deep/.wrap {
		height: 30px;
	}
</style>
